package com.example.learnspring.controller;

import com.example.learnspring.entity.Result;
import com.example.learnspring.entity.User;
import com.example.learnspring.service.UserServiceImpl;
import com.example.learnspring.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@RestController
public class LoginController {

    @Autowired
    private UserServiceImpl userService;
    @PostMapping("/login")
    public Result login(@RequestBody User user){
        try{

            Map<String, Object> claims =  new HashMap<>();
            User dbUser = userService.getUser(user);

            claims.put("username", dbUser.getUsername());
            claims.put("id", dbUser.getId());
            String jwt = JwtUtil.generateToken(claims);
            return Result.success(jwt);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @GetMapping("/logout")
    public Result logout(String token){
        try{
            Claims claims = JwtUtil.getClaimsFromToken(token);
            String username = claims.get("username").toString();
            return Result.success(username);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
